<template lang="pug">
  .page
    .search-form.mb-10.pl-10.pr-10
      Row(type="flex" justify="start")
        Col.pr-20.mb-15(span="8")
          span.label-txt.w80 模板名称：
          Input(v-model="tName" placeholder="请输入" clearable)
        Col.pr-20.mb-15(span="8")
          span.label-txt.w110 销售产品类型：
          Select(v-model="productType" clearable)
            Option(v-for="(item,index) in productTypeList" :value="item.text" :key="index") {{item.text}}
        Col.pr-20.mb-15(span="8")
          Button(type="info" @click="searchBtn") 查询
    .pl-20.pr-20.bg-white
      Table.hasTitle-table.beautiful-table(width="100%" :loading="loading" stripe :columns="setThead" :data="listData" @on-selection-change="tableSelectChange")
        .pr-24.pl-24(slot="header")
          .pull-right.table-title-btns
            Button.mr-15(type="info" @click="createBtn") 新增模板
        template(slot-scope="{ row, index }" slot="fileName")
          .u-d-info(@click="downloadFile(row.fileName, row.filePath)") {{row.fileName}}
        template(slot-scope="{ row, index }" slot="action_2")
          Button.mr-5(type="info" size="small" @click="reviseBtn(row)") 编辑
          Button.mr-5(v-if="row.enable" type="warning" size="small" @click="enableTemplate(row.id, 0)") 禁用
          Button.mr-5(v-else type="info" size="small" @click="enableTemplate(row.id, 1)") 启用
        .clearfix.pl-20.pr-20(slot="footer")
          Page(:total="codeTotal" :current="PageIndex" :page-size="PageSize" prev-text="上一页" next-text="下一页" @on-change="pageChangeFn" show-total @on-page-size-change="onpageSizeChange" show-sizer :page-size-opts="[10, 20, 30, 50, 100]")
    Modal(v-model="modalShow" :title="modalTitle" width="700")
      Form.is-revise(ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="130")
        FormItem(label="销售产品类型：" prop="productType")
          Select(v-model="formValidate.productType" clearable :disabled="isRevise")
            Option(v-for="(item,index) in productTypeList" :value="item.text" :key="index") {{item.text}}
        FormItem(label="模板名称：" prop="tName")
          Input(v-model="formValidate.tName" placeholder="请输入" :disabled="isRevise")
        FormItem.ivu-form-item-required(label="选择文件：")
          Upload(
            :before-upload="createHandleUpload"
            multiple ref="addUpload"
            :show-upload-list="true"
            action=""
            accept="application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
            :format="['doc','docx']"
            )
            Button(type="info" icon="ios-cloud-upload-outline") 点击上传
          .my-tag.mr-20(v-if="templateFile")
            .my-tag-inner {{formValidate.fileName}}
            .img-close.ivu-icon.ivu-icon-ios-close(@click="deleteFile")
          .ivu-form-item-error-tip(v-if="hasFile") 模板文件不能为空
          .text-gray-9.font-13 温馨提示：请用Microsoft Word保存的文件上传，禁用WPS等其他软件保存的文件
        FormItem(v-if="!isRevise" label="启用：")
          i-switch(v-model="switch1" @on-change="switchChange")

      template(slot="footer")
        Button(type="info" @click="handleSubmit('formValidate')") 提交
        Button(@click="modalShow = false") 取消
</template>

<script>
import commerceContractApi from '@/api/commerceContract.api.js'
import Mixin from '../ccMixin.js'
import theadMixin from '../theadMixin.js'
import config from '@/config'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro

export default {
  name: 'examine_cc',
  components: {
  },
  data () {
    return {
      isRevise: false, // 是否处于修改状态
      uploadBaseUrl: baseUrl,
      thead: ['selection', 'tNo', 'tName', 'productType', 'fileName', 'createUser', 'createTime', 'action_2'],
      listData: [],
      tName: '', // 模板名称
      productType: '', // 销售产品类型
      loading: false,
      codeTotal: 0,
      PageIndex: 1,
      PageSize: 10,
      modalTitle: '',
      switch1: true,
      modalShow: false,
      templateFile: null,
      hasFile: false,
      formValidate: {
        productType: '',
        tName: '',
        enable: 1,
        id: '',
        fileName: null
      },
      ruleValidate: {
        productType: [
          { required: true, message: '产品类型不能为空', trigger: 'change' }
        ],
        tName: [
          { required: true, message: '模板名称不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  mixins: [Mixin, theadMixin],
  computed: {
    setThead () {
      return this.getTableColumns(this.thead)
    }
  },
  created () {
    this.getList()
  },
  methods: {
    // 获取模板列表
    getList () {
      commerceContractApi.GetTemplateList({
        tName: this.tName,
        productType: this.productType,
        PageIndex: this.PageIndex,
        PageSize: this.PageSize
      }).then(res => {
        if (res.data.success) {
          this.listData = res.data.data
          this.codeTotal = res.data.totalRows
        } else {
          
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },
    // 新建客户弹窗
    createBtn () {
      this.modalTitle = '新增模板'
      this.isRevise = false
      this.templateFile = null
      this.hasFile = false
      this.formValidate = {
        productType: '',
        tName: '',
        enable: 1,
        id: '',
        fileName: null
      }
      this.$refs['formValidate'].resetFields()
      this.modalShow = true
    },
    reviseBtn (row) {
      // this.$refs['formValidate'].resetFields()
      this.modalTitle = '编辑模板'
      this.formValidate = row
      this.isRevise = true
      this.templateFile = null
      this.hasFile = false
      this.modalShow = true
    },
    // 上传模板附件
    createHandleUpload (file) {
      console.log(file)
      this.templateFile = file
      this.hasFile = false
      this.formValidate.fileName = file.name
      return false
    },
    deleteFile () {
      this.templateFile = null
      this.formValidate.fileName = ''
    },
    // 提交按钮
    handleSubmit (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          if (this.templateFile) {
            this.submitTemplate()
          } else {
            this.hasFile = true
          }
        } else {
        }
      })
    },
    // 提交模板
    submitTemplate () {
      let formData = new FormData()
      if (this.isRevise) {
        formData.append('id', this.formValidate.id)
      } else {
        formData.append('id', '')
      }
      formData.append('atta', this.templateFile)
      formData.append('producttype', this.formValidate.productType)
      formData.append('tname', this.formValidate.tName)
      formData.append('enable', this.formValidate.enable)
      commerceContractApi.PostContractTemplate(formData).then(res => {
        if (res.data.success) {
          this.$Message.success(res.data.message)
          this.modalShow = false
          this.hasFile = false
          this.templateFile = null
          this.formValidate = {
            productType: '',
            tName: '',
            enable: 1,
            id: '',
            fileName: null
          }
          this.$refs['formValidate'].resetFields()
          this.getList()
        } else {
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },
    // 启用禁用
    enableTemplate (id, val) {
      commerceContractApi.EnableTemplate({
        ID: id,
        Enable: val
      }).then(res => {
        if (res.data.success) {
          this.$Message.success(res.data.message)
          this.getList()
        } else {
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },
    // 下载文件模板
    downloadFile (fileName, filePath) {
      let objectUrl = filePath
      console.log(objectUrl)
      const link = document.createElement('a')
      link.download = fileName
      link.href = objectUrl
      link.click()
    },
    // 查询
    searchBtn () {
      this.PageIndex = 1
      this.getList()
    },
    // 客户导入
    importBtn () {

    },
    // 客户导出
    exportBtn () {

    },
    switchChange (val) {
      if (val) {
        this.formValidate.enable = 1
      } else {
        this.formValidate.enable = 0
      }
    },
    tableSelectChange () {

    },
    pageChangeFn (val) {
      this.PageIndex = val
      this.getList()
    },
    onpageSizeChange (val) {
      this.PageSize = val
      this.getList()
    }
  }
}
</script>

<style>

</style>
